package com.inspur.edp.common.type.spi;

import com.inspur.edp.common.type.exception.TypeException;
import com.inspur.edp.common.type.enhanced.EnhancedServiceLoader;
import io.iec.edp.caf.commons.utils.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author lizhaorui
 * @description TODO
 * @date 2024/12/11 10:24
 */
public class TypeProviderFactory {

    private final static Object lockObject = new Object();

    private static Map<String, TypeResourceProvider> PROVIDER_MAP;

    public static TypeResourceProvider getProvider(String sourceType) {
        if (PROVIDER_MAP == null) {
            synchronized (lockObject) {
                if (PROVIDER_MAP == null) {
                    ConcurrentHashMap<String, TypeResourceProvider> temp = new ConcurrentHashMap<>();
                    List<Object> objectList = EnhancedServiceLoader.loadFile("META-INF/services/" + TypeResourceProvider.class.getName(), TypeProviderFactory.class.getClassLoader());
                    for (Object obj : objectList) {
                        TypeResourceProvider provider = (TypeResourceProvider) obj;
                        temp.put(provider.getKind(), provider);
                    }
                    PROVIDER_MAP = temp;
                }
            }
        }
        if (StringUtils.isEmpty(sourceType)) {
            throw new TypeException("source type can not be empty.");
        }
        return PROVIDER_MAP.get(sourceType);
    }

}
